/**
 * 
 */
package org.swing.utility.common.datetime;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.swing.utility.common.datetime.DateParser.InvalidDateException;

/**
 * @author lqnhu
 *
 */
public class Iso8601Date extends Date {
	private static final ThreadLocal<DateFormat> iso8601DateFormatter = new ThreadLocal<DateFormat>() {
		protected synchronized DateFormat initialValue() {
			return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
		}
	};

	public Iso8601Date(final String dateStr) throws InvalidDateException {
		super(DateParser.parse(dateStr).getTime());
		truncateMilliseconds();
	}

	public Iso8601Date(final Date date) {
		super(date.getTime());
		truncateMilliseconds();
	}

	public String toString() {
		return iso8601DateFormatter.get().format(this);
	}

	private void truncateMilliseconds() {
		long time = getTime();
		long mod = time % 1000;
		if (mod != 0) {
			super.setTime(time - mod);
		}
	}
}
